<?php
/**
 * 《盘点信息》实现类
 *
 * @author 孙晓晔
 * @version $Id: Out.class.php 1048 2010-04-06 04:43:12Z sunxy $
 */

require_once(dirname(__FILE__) . '/Amount.class.php');

class PanDian extends Amount {
	public $tbl = Constant::tbl_material_pandian;

	public $status = array(
		'-' => '请选择',
		'1' => '有效',
		'2' => '无效',
	
		'9' => '其它',
	);
	
	public $orderby = array(
		'-' => '请选择',
		'material' => '材料',
		'category' => '大类',
		'subclass' => '小类',
		'standard' => '规格',
	
		'amount' => '数量',
		'price' => '单价',
		'total' => '总价',

		'emp' => '盘点人',
		'date' => '盘点日期',

		'1' => '创建时间',
	);

	public $groupby = array(
		'-' => '请选择',
		'material' => '材料',
		'emp' => '盘点人',
		'status' => '状态',
	
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);
	}

	function find($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-3 month'));

		$controller->display($request, 'material/amount/pandian/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == 'mold') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = Name::mold($row['mold']);
		}

		if ($px == 'category') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['category'];
		}

		if ($px == 'subclass') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['subclass'];
		}
		
		if ($px == 'date') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['date'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$material_s = $this->_input($request['material_s']);

		$category_s = $request['category_s'];
		$subclass_s = $request['subclass_s'];

		$name_s = addslashes(trim($request['name_s']));
		
		$date1_s = $request['date1_s'];
		$date2_s = $request['date2_s'];

		$where = " WHERE 1=1";

		if (!empty($material_s)) {
			$where .= " AND material = '" . $material_s . "'";
		}

		if (!empty($category_s) && $category_s <> '-') {
			$where .= " AND category = '" . $category_s . "'";
		}

		if (!empty($subclass_s) && $subclass_s <> '-') {
			$where .= " AND subclass = '" . $subclass_s . "'";
		}

		if (!empty($name_s)) {
			$where .= " AND (name LIKE '%" . $name_s . "%' OR standard LIKE '%" . $name_s . "%' OR content LIKE '%" . $name_s . "%')";
		}

		if (!empty($date1_s)) {
			$where .= " AND date >= '" . $date1_s . "'";
		}
		
		if (!empty($date2_s)) {
			$where .= " AND date < '" . $date2_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}
	
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'material/amount/pandian/list');
		return true;
	}
	
	function xls($controller, $request) {
		$this->pretreat($controller);
		
		$this->findPara($controller, $request);

		$request['tpl'] = "xls";

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'material/amount/pandian/list');
		return true;
	}
	
	function add($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		require_once(dirname(__FILE__) . '/Amount.class.php');
		$aa = new Amount();
		$row = $aa->_view($id);

		$controller->assign_by_ref('result', $row);
				
		$name = addslashes($row['name']);
		$standard = addslashes($row['standard']);
			
		$controller->assign_by_ref('history', $this->_list($name, $standard));
		
		$controller->display($request, 'material/amount/pandian/add');
		return true;
	}
	
	function _list($name, $standard) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE name = '%s' AND standard = '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, $this->tbl, $name, $standard);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['emp_t'] = Name::emp($row['emp']);

			$ret[] = $row;
		}

		return $ret;
	}
	
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		
		$date = $request['date'];
		$pd = $request['amount'];
		$emp = $this->_input($request['emp']);		
		$content = addslashes($request['content']); 
		
		$oper = $_SESSION['id'];
		
		$this->_pandian($id, $date, $pd, $emp, $content, $oper);

		$controller->display($request, 'info');
		return true;
	}
	
	function _pandian($id, $date, $pd, $emp, $content, $oper, $kc = '') {
		require_once(dirname(__FILE__) . '/Amount.class.php');
		$aa = new Amount();
		
		$db = newdb($this->dsn_w);
		if ($row = $aa->_view($id)) {
			$name = addslashes($row['name']);
			$standard = addslashes($row['standard']);
			
			// print_r($row);
			
			if (strlen($kc) == 0) {
				$kc = $row['amount'];
			}
			
			$profit = $pd - $kc;
			$amount = $profit + $row['amount'];			
			$total = $row['price'] * $profit;
						
			$fmt = "INSERT INTO %s(material, category, subclass, emp, date, place, name, standard, kc, pd, amount, unit, price, total, content, oper, createtime) ";
			$fmt .= "VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now())";
			$sql = sprintf($fmt, $this->tbl, $row['material'], $row['category'], $row['subclass'], $emp, $date, $row['place'], $name, $standard, $kc, $pd, $profit, $row['unit'], $row['price'], $total, $content, $oper);
			// echo $sql . "\n";
			$db->query($sql);
			
			$aa->_update_amount($id, $amount);
			
			return true;
		}
		
		return false;
	}
	
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/amount/pandian/edit');
		return true;
	}

	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$date = $request['date'];
		$place = $request['place'];

		$name = addslashes($request['name']);
		$standard = addslashes($request['standard']);
		$unit = $request['unit'];
		$price = $request['price'];
		
		$kc = $request['kc'];
		$pd = $request['pd'];
		$amount = $request['amount'];
		$total = $request['total'];
		
		$content = addslashes($request['content']);
		$status = $request['status'];
		
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s', date = '%s', place = '%s', name = '%s', standard = '%s', unit = '%s', price = '%s', kc = '%s'";
		$fmt .= ", pd = '%s', amount = '%s', total = '%s', content = '%s', status = '%s', modifytime = NOW() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $emp, $date, $place, $name, $standard, $unit, $price, $kc, $pd, $amount, $total, $content, $status, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return true;
		}
			
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);		

		$controller->assign_by_ref('result', $row);

		require_once 'Material.class.php';
		$material = new Material();
		$controller->assign_by_ref('material', $material->_view($row['material']));

		$controller->display($request, 'material/amount/pandian/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}

		$row = $this->_view_t($row);
		
		return $row;
	}
	
	function delete($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
			
			$row = $this->id($this->tbl, $id);
			
			if ($this->_is_delete($row)) {
				$fmt = "DELETE FROM %s WHERE id = '%s'";
				$sql = sprintf($fmt, $this->tbl, $id);
				// debug($sql);
				$db->query($sql);
			}
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}

		return false;
	}
	
	function z($controller, $request) {
		$a = array('file' => "/home/sunxy/0324.xls", 'date'=>'2011-03-31', 'emp'=>'1499');
		// $a = array('file' => "/home/sunxy/zz.xls", 'date'=>'2010-12-15', 'emp'=>'1155');

		$this->_xls($a['file'], $a['date'], $a['emp']);

		logdate($controller, $request);
		return true;
	}
	
	function _xls($file, $date, $emp) {
		require_once APP_LIB . 'excel_class.php';

		Read_Excel_File($file, $return);

		$a = array_keys($return);
		$ret = array();
		while (list($k, $v) = each($a)) {
			$buf = $return[$v];

			$ret[] = $this->_xls_sheet($buf, $date, $emp);
		}
		
		print_r($ret);
	}

	function _xls_sheet($buf, $date, $emp) {
		$txt = sprintf("/home/sunxy/%s-%s.txt", $emp, $date);

		$db = newdb($this->dsn_w);
		
		$ret = array('a'=>0, 'b'=>0);
		for($j = 1; $j < count($buf); $j++) {
			$a = $buf[$j];
			
			if (!is_numeric($a[0])) {
				echo "S";
				continue;
			}
			
			// print_r($a);
			
			if ($this->_xls_sheet_a($a, $date, $emp)) {
				$ret['a']++;
			} else {
				$ret['b']++;
				
				// print_r($a);
				$content = sprintf("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s", $a[1], $a[2], $a[3], $a[4], $a[5], $a[6], $a[7], $a[8]);
				txt($content, $txt);
			}

			echo ".";
		}
		
		return $ret;
	}
	
	function _xls_sheet_a($a, $date, $emp) {
		$id = trim($a[1]);
		
		$kc = trim($a[5]);
		$pd = trim($a[6]);
		$content = addslashes($a[8]);
		
		return $this->_pandian($id, $date, $pd, $emp, $content, '101', $kc);
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email('121');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '库存盘点';
		
		$cc = array(
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'place'),
			// '更新信息，金额大于100'=>array('w' => "price*amount > 100 AND DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -20 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'place'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			echo "222";
			return;
		}
		
		$controller->clear_assign('result');
		
		$body = $this->_tj_html($controller, $request, 'material/amount/pandian/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}

	function tjw($controller, $request) {
		$bb = $this->_list_email('121');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '库存盘点（周报）';
		
		$cc = array(	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'place'),
			// '更新信息，金额大于500'=>array('w' => "price*amount > 500 AND DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -100 WEEK), '%Y-%V') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'place'),			
		);
		
		$this->_tj_cc($controller, $cc);
		
		$aa = array(
			'一个星期之内'=>array('w' => "WHERE status = 1 AND createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')"),
			'一个月之内'=>array('w' => "WHERE status = 1 AND createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 MONTH), '%Y-%m-%d')"),
			'三个月之内'=>array('w' => "WHERE status = 1 AND createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')"),
			'半年之内'=>array('w' => "WHERE status = 1 AND createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -6 MONTH), '%Y-%m-%d')"),
			'一年之内'=>array('w' => "WHERE status = 1 AND createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')"),
			'全部'=>array('w' => "")
		);
		
		$this->_tj_bb($controller, $aa);

		$body = $this->_tj_html($controller, $request, 'material/amount/pandian/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function _tj2($v) {
		$this->result_s = 10;
		$this->groupby_s = 'material';
			
		$s = $this->groupby_s;

		if (!empty($v['w'])) {
			$fmt = "SELECT %s AS a, SUM(price*amount) AS c FROM %s a %s GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $v['w'], $s);
		} else {
			$fmt = "SELECT %s AS a, SUM(price*amount) AS c FROM %s a GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $s);
		}		
		echo $sql . "\n";

		return $this->_group_tj2($sql);
	}
}

function txt($s, $file = null) {
	if (empty($s)) {
		return false;
	}

	$fd = @fopen($file, "a+");
	@fwrite($fd, $s . "\n");
	@fclose($fd);
}
?>
